// pages/movies/more-movie/more-movie.js
var app = getApp()
var util = require('../../../utils/utils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: '',
    totalCount: 0,
    requestUrl: '',
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    var category = options.category
    wx.setNavigationBarTitle({
      title: category
    })
    var dataUrl = ''
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + '/v2/movie/in_theaters'
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase + '/v2/movie/coming_soon'
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + '/v2/movie/top250'
        break;
    }
    this.setData({
      requestUrl: dataUrl
    })
    util.http(dataUrl, this.processDoubanData)
  },
  // onScrollLower() {
  //   // console.log("加载更多")
  //   var nextUrl = this.data.requestUrl + '?start=' + this.data.totalCount + '&count=20'
  //   util.http(nextUrl, this.processDoubanData)
  //   wx.showNavigationBarLoading()
  // },
  onReachBottom() {
    // console.log("加载更多")
    var nextUrl = this.data.requestUrl + '?start=' + this.data.totalCount + '&count=20'
    util.http(nextUrl, this.processDoubanData)
    wx.showNavigationBarLoading()
  },
  onPullDownRefresh() {
    var refreshUrl = this.data.requestUrl + '?start=0&count=20'
    util.http(refreshUrl, this.processDoubanData)
    this.data.movies = {}
    this.data.isEmpty = true
    this.data.totalmovies = 0
    wx.showNavigationBarLoading()
    wx.stopPullDownRefresh()
  },
  processDoubanData(moviesDouban) {
    // console.log(moviesDouban)
    var movies = []
    for (const idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx]
      var title = subject.title
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...'
      }
      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp)
    }
    var totalmovies = {}
    // 更新刷新加载的数据，与已请求数据合并
    if (!this.data.isEmpty) {
      totalmovies = this.data.movies.concat(movies)
    } else {
      totalmovies = movies
      this.data.isEmpty = false
    }
    this.setData({
      movies: totalmovies
    })
    wx.hideNavigationBarLoading()
    this.data.totalCount += 20
  },
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieid;
    console.log(movieId)
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId
    })
  }
})